package dcl.software.filesync.server.transfer;

import java.util.Date;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Repository;

import com.mongodb.client.MongoCollection;

import dcl.software.filesync.server.BaseRepository;
import dcl.software.filesync.server.auth.User;

@Repository
@DependsOn("mongoClient")
public class FileRepository extends BaseRepository {
	@Value("${mongo.collection.files}")
	private String filesCollection;

	@Override
	protected String getCollectionString() {
		return filesCollection;
	}

	public String save(FileUploadItem properties, User user) {
		MongoCollection<Document> collectionSession = getCollectionSession();
		Document document = new Document("fileName", properties.getFileName());
		document.append("localPath", properties.getLocalPath());
		document.append("serverPath", properties.getServerPath());
		document.append("macAddress", properties.getMacAddress());
		document.append("macAddress", user.getUserName());
		Date date = new Date();
		document.append("insertDate", date);
		document.append("lastModified", date);
		document.append("properties", new Document(properties.getProperties()));
		collectionSession.insertOne(document);
		return ((ObjectId) document.get("_id")).toString();
	}

	public void updateFileName(FileUploadItem properties, String id) {
		MongoCollection<Document> collectionSession = getCollectionSession();
		Document document = new Document("properties", new Document(properties.getProperties()));

		collectionSession.updateOne(new Document("_id", new ObjectId(id)), new Document("$set",
		        new Document("serverPath", properties.getServerPath())).append("$currentDate", new Document("lastModified", true)));
	}
}
